import re

from users.models import User
from rest_framework import serializers
from django.contrib.auth.models import Group



class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')

        extra_kwargs = {
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 5
            },
            'username': {
                'max_length': 20,
                'min_length': 5
            },

        }

    def validate_mobile(self, attrs):
        if not re.match(r'1[3-9]\d{9}', attrs):
            raise serializers.ValidationError('手机号格式不正确')
        return attrs



    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.is_staff=True
        user.save()
        return user

    def update(self, instance, validated_data):
        user = super().update(instance,validated_data)
        user.set_password(validated_data['password'])

        user.save()
        return user


class GroupSerializer(serializers.ModelSerializer):

    class Meta:

        model = Group
        fields = '__all__'